package org.harsh.transmission.common.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import org.harsh.common.Config;
import org.harsh.common.crypt.AesCrypt;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.List;

@Component
public class PlainCryptMsgPackCodec extends MessageToMessageCodec<ByteBuf, ByteBuf> {

    /**
     * encode
     * @param ctx
     * @param buf
     * @param list
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception {
        byte[] data = new byte[buf.readableBytes()];
        buf.getBytes(buf.readerIndex(), data);
        byte[] sharedKey = Config.DEFAULT_KEY.getBytes(Config.DEFAULT_CHARSET);
        AesCrypt crypt = new AesCrypt(sharedKey);
        crypt.init();
        byte[] cryptData = crypt.encrypt(data);
        list.add(Unpooled.copiedBuffer(cryptData));
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception {
        byte[] data = new byte[buf.readableBytes()];
        buf.readBytes(data);
        byte[] sharedKey = Config.DEFAULT_KEY.getBytes(Config.DEFAULT_CHARSET);
        AesCrypt crypt = new AesCrypt(sharedKey);
        crypt.init();
        byte[] cryptData = crypt.decrypt(data);
        list.add(Unpooled.copiedBuffer(cryptData));
    }
}
